package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dto.StudentDTO;
import com.example.mapper.StuMapper;
import com.example.pojo.PageBean;
import com.example.pojo.Student;
import com.example.service.StuService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class StuServiceImpl extends ServiceImpl<StuMapper, Student> implements StuService {

    @Override
    public PageBean<Student> find(StudentDTO studentDTO) {
        //1.获取数据
        String id = studentDTO.getId();
        String name = studentDTO.getName();
        String college = studentDTO.getCollege();
        Integer page = studentDTO.getPage();
        Integer pageSize = studentDTO.getPageSize();

        //2.分页条件
        Page<Student> p = Page.of(page, pageSize);

        //3.排序条件
        p.addOrder(new OrderItem("update_time", false));

        //4.查询条件
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<Student>()
                .eq(id != null && id != "", Student::getId, id)
                .like(name != null && name != "", Student::getName, name)
                .like(college != null && college != "", Student::getCollege, college);

        //5.分页查询
        page(p, wrapper);

        //6.封装数据并返回
        return PageBean.of(p.getTotal(), p.getRecords());
    }

    @Override
    public void saveStudent(Student stu) {
        // 创建 DateTimeFormatter 用于解析 ISO 8601 格式的日期时间字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

        // 解析日期时间字符串为 LocalDateTime 对象
        LocalDateTime entryTime = LocalDateTime.parse(stu.getEntryTime().toString(), formatter);

        stu.setEntryTime(entryTime);
        save(stu);
    }

    @Override
    public void updateStudent(Student stu) {
        stu.setUpdateTime(LocalDateTime.now());
        updateById(stu);
    }
}
